<?php

    class News_Categories extends ActiveRecord {
        
        function News_Categories()
        {
            $conf = array('table'=>DB_PREFIX.'news_categories');
            $this->ActiveRecord($conf);
        }
        
        function validate()
        {
            $this->validates_presence_of('name');
            $this->validates_uniqueness_of('name');
            $this->validates_format_of('name',"!^[_\d\w -]+$!",'Category Name can not contain special characters');
        }
        
        function after_validation()
        {
            $this->set('index_name', $this->create_index_name($this->get('name')));
        }
        
        function before_delete()
        {
            $this->saved_id = $this->get('id');
            $this->saved_parent_id = $this->get('parent_id');
            if ( $this->saved_id == 1 )
            {
                return false;
            }
        }

        function after_delete()
        {
            $this->db->Execute("UPDATE `{$this->table}` SET parent_id=? WHERE parent_id=?",
                               array($this->saved_parent_id,$this->saved_id));
            $this->db->Execute('UPDATE `'.DB_PREFIX.'categories_news` SET news_category_id=? WHERE news_category_id=?',
                              array($this->saved_parent_id,$this->saved_id));
        }
        
        function get_categories_by_news($id)
        {
            return $this->db->GetAssoc('SELECT 
                                        c.index_name,c.name 
                                      FROM 
                                        `'.$this->table.'` c, 
                                        `'.DB_PREFIX.'categories_news` n 
                                      WHERE 
                                        n.news_id=?
                                      AND
                                        n.news_category_id = c.id
                                      ORDER BY name',
                                      array($id));
        }
        
        function categories_as_list()
        {
            return $this->db->GetAssoc('SELECT id, name FROM `'.$this->table.'` ORDER BY name');
        }
        
        function post_count_by_category($id)
        {
            return $this->db->GetOne("SELECT count(news_id) FROM `".DB_PREFIX."categories_news` WHERE news_category_id = ?",
                                      array($id));
        }
        
        function get_report_count(&$fields)
        {
            $fields['Post Count'] = $this->post_count_by_category($fields['id']);
        }
        
        function get_paged_categories()
        {             
             $sql = 'SELECT c.id, c.name, c.index_name `Post Count` FROM `'.$this->table.'` c ORDER BY c.name ';
             $pager = $this->pager($sql);             
             $pager->row_key = 'id';
             $pager->rs_callback = array($this,'get_report_count');
             return $pager;
         }
    }
        

?>